const path = require('path'); // eslint-disable-line
const srcPath = path.resolve(process.cwd(), './src');
const ExtractTextPlugin = require('extract-text-webpack-plugin'); // eslint-disable-line
const IS_DEV = process.env.NODE_ENV !== 'production';

const theme = require(path.resolve(srcPath, 'common/less/theme.js')); // eslint-disable-line

module.exports = (config) => { // eslint-disable-line
  const ExtractTextInstance = new ExtractTextPlugin({filename: '[name].min.css', allChunks: true});
  let plugins = config.plugins.filter((plg) => {
    // sinx 里存在一个 ExtractTextPlugin 了，过滤掉。
    let isInstance = plg.hasOwnProperty('filename') && plg.filename === '[name].min.css';
    return !isInstance;
  }).concat(ExtractTextInstance);

  config = {
    ...config,
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: 'babel-loader',
        }, {
          test: /\.css/,
          loader: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: ['css-loader'],
          }),
        }, {
          test: /\.(png|jpg|gif)$/,
          loader: 'url-loader',
          query: {
            limit: 10000,
            // CSS图片目录
            name: IS_DEV ? '[path][name].[ext]' : 'assets/[name].[ext]',
          }
        }, {
          test: /\.less$/,
          exclude: [/node_modules/, srcPath + '/common/less'],
          loader: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: [
              {
                loader: 'css-loader',
                options: {
                  localIdentName: (IS_DEV ? '[local]_' : '[sx]') + '[hash:base64:6]',
                  modules: true,
                  camelCase: true,
                  sourceMap: IS_DEV
                }
              }, {
                loader: 'less-loader',
                options: {
                  sourceMap: IS_DEV,
                  modifyVars: theme
                }
              }],
          }),
        }, {
          test: /\.less$/,
          include: [/node_modules/, srcPath + '/common/less'],
          loader: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: ['css-loader', {
              loader: 'less-loader',
              options: {
                modifyVars: theme
              }
            }],
          }),
        },
      ]
    },
    plugins,
    resolve: {
      ...config.resolve,
      alias: {
        components: srcPath + '/components',
        common: srcPath + '/common',
        modules: srcPath + '/modules',
        stores: srcPath + '/stores',
      }
    }
  };
  return config;
};
